#include "gWeapon.h"

gWeapon::gWeapon()
{
	m_attach   = 0;
	m_distance = 0;
	m_target   = 0;

	m_projMesh    = 0;
	m_projTexture = 0;
	m_projCount   = 0;
	m_projAmount  = 0;
	m_projRadius  = 0;
	m_projSpeed   = 0;
	m_projDamage  = 0;
	m_projList    = 0;
}
gWeapon::~gWeapon()
{

}

void gWeapon::initWeapon(
	V3DF*    a_attach,
	float    a_distance,
	clkMesh* a_target)
{
	m_attach   = a_attach;
	m_distance = a_distance;
	m_target   = a_target;
}

void gWeapon::initProjectile(
	char* a_projMesh,
	char* a_projTexture,
	int   a_projAmount,
	float a_projRadius,
	float a_projSpeed,
	float a_projDamage,
	Dynamic_Array<gProjectile*>* a_projList)
{
	m_projMesh    = a_projMesh;
	m_projTexture = a_projTexture;
	m_projAmount  = a_projAmount;
	m_projRadius  = a_projRadius;
	m_projSpeed   = a_projSpeed;
	m_projDamage  = a_projDamage;
	m_projList    = a_projList;
}

void gWeapon::release()
{
	
}

void gWeapon::input()
{
	if(m_din->mousePress(BTN_LEFT))
		createProjectile();
}

void gWeapon::update()
{
	m_trn = *m_attach;

	V2DF  cur;
	V3DF  ori, dir;
	bool  hit = false;
	float dis = 0;

	m_din->mousePosition(&cur.x,&cur.y);
	m_d3d->projCoord(&m_target->getMesh(),&hit,&dis,&ori,&dir,cur);

	if(hit)
	{
		V3DF pA = m_trn;
		V3DF pB = (ori+(dir*dis))*(V3D_XZ*m_target->getScl());
		float a = DEGREE(polarAngleXZ((pB-pA).normal()));

		m_rot.y = a;
	}

	gObject::update();
}

void gWeapon::createProjectile()
{
	if(m_projCount < m_projAmount || m_projAmount == -1)
	{
		if(m_projAmount != -1)
			m_projCount++;

		V3DF pos = m_trn + (m_look * m_distance);
		V3DF vel = m_look * m_projSpeed;

		Physic_Object_Frame frame;
		frame.m_maxSpeed = m_projSpeed;
		frame.m_drag     = 1.0f;
		frame.m_radius   = m_projRadius;
		frame.m_position = Vector3(pos.x,pos.y,pos.z);
		frame.m_velocity = Vector3(vel.x,vel.y,vel.z);

		gProjectile *tempProj = 0;
		tempProj = new gProjectile;
		tempProj->init(FRAMEWORKS_MEM_REG,m_world);
		tempProj->initMesh(m_projMesh,V3D_ZERO,V3D_ZERO,V3D_ONES,V3D_ZERO);
		tempProj->initTexture(m_projTexture);
		tempProj->initPhysics(m_world->CreateObject(&frame));
		tempProj->update();

		m_projList->insertToEnd(tempProj);
	}
}